package solution5;

public class Solution {

    // Time complexity: O(n^2)
    // Space complexity: O(1)
    public String longestPalindrome(String s) {
        int start = 0;
        int end = 0;
        int n = s.length();
        for (int i = 0; i < n; i++) {
            //两种情况
            int len1 = expandArroundCenter(s, i ,i);
            int len2 = expandArroundCenter(s, i, i+ 1);
            int len = Math.max(len1, len2);
            if (len > end - start) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        return s.substring(start, end + 1);
    }

    private int expandArroundCenter(String s, int left, int right) {
        int L = left;
        int R = right;
        int n = s.length();
        while (L >=0 && R < n && s.charAt(L) == s.charAt(R)) {
            L--;
            R++;
        }
        return R - L - 1;
    }
}
